package com.geeklei.media.ui;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.geeklei.media.ui.controller.LifeCycleManager;
import com.geeklei.media.ui.utils.Screen;
import com.geeklei.media.ui.widget.LoadingCycle;
import com.geeklei.videoplayer.GeekleiVideoView;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by leixun on 2016/6/23.
 */

/**
 * 使用步骤：
 * onCreate（）中执行 1、2、3步
 * 1:   new GeekleiMediaUi() 创建实例 并 实现相关接口参数
 * 2:   设置Fragment或者Activity的布局 setContentView(getContentView())
 * 3:   自定义的布局添加：addChildView()
 * 4:   fragment actvity的各个生命周期中调用：onStart onResume onPause onStop onDestory onConfiguratonChanged onKeyDown
 */
public class GeekleiMediaUi {
    private ControllerView mControllerView;
    private View mView;
    private FrameLayout mChildView;
    private com.geeklei.media.ui.FullScreenVideoController mFullScreenController;
    private PortraitScreenVideoController mPortraitScreenVideoController;
    private boolean mEnablePortraitScreen = false;
    protected GeekleiVideoView mVideoView = null;

    boolean isOpenHardWareSpeed = false;
    VideoCycleManager mVideoCycleMgr;
    LoadingCycle mLoadingCycle;

    private Activity mActivity;

    private MediaPlayerListener mediaPlayerListener;

    private IUserEventListener iUserEventListener;
    private View mContentView;
    //    private OrientationUpdater mOrientationUpdater;
    private LifeCycleManager mLifeCycleManager = new LifeCycleManager();

    // enablePortraitScreen 竖屏是否可用
    public GeekleiMediaUi(Activity activity, @NonNull MediaPlayerListener mediaPlayerListener,
                          @NonNull IUserEventListener iUserEventListener, boolean enablePortraitScreen) {
        this.mActivity = activity;
        this.mediaPlayerListener = mediaPlayerListener;
        this.iUserEventListener = iUserEventListener;
        this.mEnablePortraitScreen = enablePortraitScreen;
        initLifeCycle();
        mContentView = onCreateView(LayoutInflater.from(mActivity));
    }

    public GeekleiMediaUi(Activity activity, @NonNull MediaPlayerListener mediaPlayerListener, @NonNull IUserEventListener iUserEventListener) {
        this(activity, mediaPlayerListener, iUserEventListener, false);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //这里控制back键的监听
        if (keyCode == event.KEYCODE_BACK) {
            if (isFullScreen()) {
                if (mFullScreenController != null && mFullScreenController.IsScreenLocked()) {
                    mFullScreenController.showLockScreen();
                    return true;
                }
                if (!mEnablePortraitScreen) {
                    getActivity().finish();
                    return false;
                } else {
                    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                    return true;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    public void addChildView(View view) {
        if (mChildView.getChildCount() == 0) {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            view.setLayoutParams(layoutParams);
            mChildView.addView(view);
        } else {
            Log.d("GeekleiMediaUi", "has a view yet");
        }
    }

    /**
     * 正真播放需要实现 mPrepared
     *
     * @param uri
     * @param titleName // 侧滑菜单点击的时候不需要showController
     *                  // 其它均需要 否则会引起状态栏显示导致的问题
     */
    public void play(Uri uri, String titleName, boolean showController) {
        if (isFullScreen()) {
            if (mFullScreenController == null || mVideoCycleMgr == null || mLoadingCycle == null) {
                enterFullScreenMode();
            }
            if (showController) {
                this.mFullScreenController.showController(true);
            }
//            else{
//                this.mFullScreenController.hidePhoneStatusBar();
//            }
            mFullScreenController.updateStatus(titleName, "");
        } else {
            if (mPortraitScreenVideoController == null || mVideoCycleMgr == null || mLoadingCycle == null) {
                enterPortraitScreenMode();
            }
        }
        if (mVideoCycleMgr != null) {
            mVideoCycleMgr.onVideoLoadingStart(mVideoView);
        }
        mVideoView.setVideoURI(uri);
    }

    public void play(Uri uri, String titleName) {
        play(uri, titleName, true);
    }

    public View getContentView() {
        return mContentView;
    }

    public void seekTo(int position) {
        mVideoView.seekTo(position);
    }

    public void setSpeed(float speed) {
        if (mFullScreenController != null) {
            mFullScreenController.updateSpeedStatus(speed);
        }
        mVideoView.setSpeed(speed);
    }

    public void onStart() {
        this.mLifeCycleManager.onStart();
    }

    public void onResume() {
        this.mLifeCycleManager.onResume();
    }

    public void onPause() {
        mVideoView.pause();
        this.mLifeCycleManager.onPause();
    }

    public void onStop() {
        this.mLifeCycleManager.onStop();
    }

    public void onDestroy() {
        clearVideoView();
        mActivity = null;
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
        iUserEventListener = null;
        if (mFullScreenController != null) {
            mFullScreenController.cancelProgressTimer();
        }
    }

    public void onConfigurationChanged(Configuration configuration) {
//        if (this.mOrientationUpdater != null) {
//            this.mOrientationUpdater.onConfigurationChanged(configuration);
//            this.mOrientationUpdater.setEnablePortraint(mEnablePortraitScreen);
//        }
        if (this.mEnablePortraitScreen) {
            if (configuration.orientation == 1) {
                enterPortraitScreenMode();
                setMinSize();
            } else {
                enterFullScreenMode();
                setMaxSize();
            }
        } else {
            setMaxSize();
        }
    }

    private View onCreateView(LayoutInflater inflater) {

        mView = inflater.inflate(R.layout.vp_activity_local_video_player, null, false);
        mControllerView = (ControllerView) mView.findViewById(R.id.controller);
        mChildView = (FrameLayout) mView.findViewById(R.id.childview);
        initUi();
        return mView;
    }

    private void initFullScreenController() {
        if (this.mFullScreenController == null) {
            this.mFullScreenController = (com.geeklei.media.ui.FullScreenVideoController) LayoutInflater.from(this.mControllerView.getContext()).inflate(R.layout.vp_video_fullscreen_layout, this.mControllerView, false);
            this.mControllerView.addView(this.mFullScreenController);
            this.mFullScreenController.attachActivity(mActivity, this.mControllerView, null);
            this.mFullScreenController.attachMediaPlayer(mVideoView.getmMediaPlayer(), iUserEventListener);
        }
        if (this.mLoadingCycle == null) {
            this.mLoadingCycle = new LoadingCycle(this.mControllerView);
        }
        if (this.mVideoCycleMgr == null) {
            this.mVideoCycleMgr = new VideoCycleManager();
        }
        this.mVideoCycleMgr.add(this.mLoadingCycle);
        this.mVideoCycleMgr.add(this.mFullScreenController);
    }

    private void initPortraitScreenController() {
        if (this.mPortraitScreenVideoController == null) {
            this.mPortraitScreenVideoController = (PortraitScreenVideoController) LayoutInflater.from(this.mControllerView.getContext()).inflate(R.layout.vp_video_portrait_layout, this.mControllerView, false);
            this.mControllerView.addView(this.mPortraitScreenVideoController);
            this.mPortraitScreenVideoController.attachActivity(mActivity, this.mControllerView, null);
            this.mPortraitScreenVideoController.attachMediaPlayer(mVideoView.getmMediaPlayer(), iUserEventListener);
        }
        if (this.mLoadingCycle == null) {
            this.mLoadingCycle = new LoadingCycle(this.mControllerView);
        }
        if (this.mVideoCycleMgr == null) {
            this.mVideoCycleMgr = new VideoCycleManager();
        }
        this.mVideoCycleMgr.add(this.mLoadingCycle);
        this.mVideoCycleMgr.add(this.mPortraitScreenVideoController);
        this.mPortraitScreenVideoController.showController(false);
    }

    private void enterFullScreenMode() {
        initFullScreenController();
        if (mPortraitScreenVideoController != null) {
            mPortraitScreenVideoController.hideController();
        }
        if (this.mControllerView != null) {
            this.mControllerView.setGestureListener(this.mFullScreenController);
        }
    }

    private void enterPortraitScreenMode() {
        initPortraitScreenController();
        if (mFullScreenController != null) {
            mFullScreenController.hideController();
        }
        if (this.mControllerView != null) {
            this.mControllerView.setGestureListener(this.mPortraitScreenVideoController);
        }
    }

    private void initLifeCycle() {
//        this.mOrientationUpdater = new OrientationUpdater(mActivity);
//        this.mLifeCycleManager.add(this.mOrientationUpdater);
    }

    private void initVideoView() {
        if (mVideoView == null) {
            mVideoView = new GeekleiVideoView(getActivity());
            mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);

            mVideoView.setOnCompletionListener(mOnCompletionListener);
            mVideoView.setOnErrorListener(mOnErrorListener);
            mVideoView.setOnPreparedListener(mOnPreparedListener);
            mVideoView.setOnInfoListener(mOnInfoListener);
            if (!mEnablePortraitScreen) {
                setMaxSize();
            } else {
                setMinSize();
            }
            this.mControllerView.addView(this.mVideoView, 0);
        } else {
        }
    }

    private void setMinSize() {
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                Screen.getScreenWidth(getActivity().getWindowManager()), getActivity().getResources().getDimensionPixelSize(R.dimen.player_height));
        this.mVideoView.setLayoutParams(layoutParams);
        this.mControllerView.setLayoutParams(layoutParams);
    }

    private void setMaxSize() {
        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        View mParent = mView.findViewById(R.id.controllerRl);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        mParent.setLayoutParams(params);
        this.mControllerView.setLayoutParams(params);

        RelativeLayout.LayoutParams param;
        //这里判断一下是不是pad,以1920*1080的手机分辨率做比较,如果宽高比小于1920/1080,说明是类似于pad的分辨率(以小米1平板的2048*1536为例),这时按1920:1080的比例调整画面大小
        if (1.0f * Screen.getScreenWidth(mActivity.getWindowManager()) / Screen.getScreenHeight(mActivity.getWindowManager()) < (1920 / 1080f)) {
            param = new RelativeLayout.LayoutParams(Screen.getScreenWidth(mActivity.getWindowManager()), (int) (Screen.getScreenWidth(mActivity.getWindowManager()) * (1080 / 1920f)));
        } else {
            //否则用全屏
            param = new RelativeLayout.LayoutParams(Screen.getScreenWidth(mActivity.getWindowManager()), Screen.getScreenHeight(mActivity.getWindowManager()));
        }
        param.addRule(RelativeLayout.CENTER_IN_PARENT);
        this.mVideoView.setLayoutParams(param);
//        this.mVideoView.setBackgroundResource(R.color.black);
    }

    private void initUi() {
        clearVideoView();
        initVideoView();
    }

    private void clearVideoView() {
        if (!(this.mVideoView == null || this.mControllerView == null)) {
            if (this.mVideoCycleMgr != null) {
                this.mVideoCycleMgr.onCompletion(this.mVideoView);
            }
            this.mVideoView.setOnPreparedListener(null);
            this.mVideoView.setOnInfoListener(null);
            this.mVideoView.setOnErrorListener(null);
            this.mVideoView.setOnCompletionListener(null);
            this.mVideoView.setOnBufferingUpdateListener(null);
            this.mControllerView.removeView(this.mVideoView);
        }
    }

    private IMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new IMediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(IMediaPlayer mp, int percent) {
            if (mVideoCycleMgr != null) {
                mVideoCycleMgr.onBufferingPercent(mVideoView, percent);
            }
            mediaPlayerListener.mBufferingUpdate(mp, percent);
        }
    };

    private IMediaPlayer.OnCompletionListener mOnCompletionListener = new IMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(IMediaPlayer mp) {
            if (mVideoCycleMgr != null) {
                mVideoCycleMgr.onCompletion(mVideoView);
            }
            mediaPlayerListener.mCompletion(mp);
        }
    };

    private IMediaPlayer.OnErrorListener mOnErrorListener = new IMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int what, int extra) {
            if (mVideoCycleMgr != null) {
                mVideoCycleMgr.onError(mVideoView, what, extra, mediaPlayerListener.mError(iMediaPlayer, what, extra));
            }
            return true;
        }

    };

    private IMediaPlayer.OnPreparedListener mOnPreparedListener = new IMediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(IMediaPlayer mp) {
            mediaPlayerListener.mPrepared(mp);
            if (mFullScreenController != null) {
                mFullScreenController.updatePlayingState();
            }
            if (mLoadingCycle != null) {
                mLoadingCycle.onBufferingEnd(mVideoView);
            }
        }
    };

    private IMediaPlayer.OnInfoListener mOnInfoListener = new IMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(IMediaPlayer mp, int what, int extra) {
            mediaPlayerListener.mInfo(mp, what, extra);
            switch (what) {
                case IjkMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
                    if (mVideoCycleMgr != null) {
                        mVideoCycleMgr.onInfoListener(mVideoView, what, extra);
                    }
                    break;
                case IjkMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    Log.d("leixun", "MEDIA_INFO_BUFFERING_START");
                    if (mVideoCycleMgr != null) {
                        mVideoCycleMgr.onBufferingStart(mVideoView);
                    }
                    break;
                case IjkMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    Log.d("leixun", "MEDIA_INFO_BUFFERING_END");
                    if (mVideoCycleMgr != null) {
                        mVideoCycleMgr.onBufferingEnd(mVideoView);
                    }
                    break;
//                case IjkMediaPlayer.MEDIA_INFO_CACHE_UPDATE:
//                    float p = extra / 100.00f;
//                    int progress = (int) (100 * p);
//                    if (mVideoCycleMgr != null) {
//                        mVideoCycleMgr.onInfoListener(mVideoView, what, extra);
//                    }
//                    break;
                default:
                    break;
            }
            return false;
        }
    };

    private boolean isFullScreen() {
        if (!mEnablePortraitScreen) {
            return true;
        }
        if (mActivity == null) {
            return false;
        }
        int i = mActivity.getResources().getConfiguration().orientation;
        if (i == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            return false;
        }
        return true;
    }

    private Activity getActivity() {
        return mActivity;
    }

    public IjkMediaPlayer getMeidaPlayerController() {
        return mVideoView.getmMediaPlayer();
    }

    public void start() {
        if (mFullScreenController != null) {
            mFullScreenController.start();
        }
    }

    public void pause() {
        if (mFullScreenController != null) {
            mFullScreenController.pause();
        }
    }
}
